package edu.lagou.controller;

import edu.lagou.pojo.Authcode;
import edu.lagou.pojo.Token;
import edu.lagou.service.AuthcodeService;
import edu.lagou.service.CodeService;
import edu.lagou.service.TokenService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

@RestController
@RequestMapping("/api/user")
public class UserController {

    @Reference
    private CodeService codeService;

    @Autowired
    private AuthcodeService authcodeService;

    @Autowired
    private TokenService tokenService;

    @GetMapping("/register/{email}/{password}/{code}")
    public boolean register(@PathVariable String email, @PathVariable String password, @PathVariable String code) {
        // Call Code service's validate method
        String result = codeService.validateCode(email, code);
        System.out.println(">>>> The code verification result: " + result);
        if (result.equals("0")) {
            // 验证成功保存密码
            authcodeService.savePassword(email, password);
            return true;
        }

       return false;
    }

    @GetMapping("isRegistered/{email}")
    public boolean isRegistered(@PathVariable String email)
    {
        Authcode tAuthcode = authcodeService.findByEmail(email);
        if (tAuthcode == null) {
            return false;
        }

        if (tAuthcode.getPassword().length() < 1) {
            return false;
        }

        return  true;
    }

    @GetMapping("login/{email}/{password}")
    public String login(@PathVariable String email, @PathVariable String password)
    {
        Authcode tAuthcode = authcodeService.findByEmail(email);
        if (tAuthcode instanceof Authcode) {
            if (tAuthcode.getPassword().equals(password)) {
                String token = UUID.randomUUID().toString();
                tokenService.save(email, token);
                return email;
            }
        }

        return "invalid information";
    }

    @GetMapping("info/{token}")
    public String getUserInfo(@PathVariable String token)
    {
        String email = tokenService.getEmail(token);
        return email;
    }
}
